package com.example.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.pojo.Result;
import com.example.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_DaChiZi
 * Date: 2025/9/5
 * Time: 13:49
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        System.out.println("preHandle....");
        //1.获取请求url
        String url =  req.getRequestURI().toString();
        log.info("请求的url {}",url);

        //2.判断请求url是否包含login，如果包含则放行，不包含就拦截
        if (url.contains("login")) {
            log.info("登录页面，放行！");
            return true;
        }

        //3.获取请求头中的令牌token
        String jwt = req.getHeader("token");

        //4.判断令牌是否存在，如果不存在则返回错误
        if (!StringUtils.hasLength(jwt)) {
            log.info("令牌不存在，返回错误信息");
            Result result = Result.error("NOT_LOGIN");
            // 手动转换对象为JSON格式文件-------阿里巴巴 fastJSON
            String notLogin =  JSONObject.toJSONString(result);
            resp.getWriter().write(notLogin);
            return false;
        }

        //5.解析token，如果解析失败则返回错误
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌不合法，返回错误信息");
            Result result = Result.error("NOT_LOGIN");
            // 手动转换对象为JSON格式文件-------阿里巴巴 fastJSON
            String notLogin =  JSONObject.toJSONString(result);
            resp.getWriter().write(notLogin);
            return false;
        }

        //6.放行
        log.info("令牌合法，放行！");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle....");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion....");
    }
}
